package com.diandian.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.diandian.orc.baidu.OCRUtil;
import com.diandian.service.BaiduOcrService;
import com.diandian.util.ImageUtil;
import com.diandian.util.PathUtil;
import com.diandian.util.StringUtil;
import com.diandian.util.VerbalAssociation;
import com.diandian.vo.Product;

@Controller
@RequestMapping(value = "/ocr")
public class OcrController {

	private static Logger log = LoggerFactory.getLogger(OcrController.class);
	
	
	@RequestMapping(value = "/to_ocr")
	public String tofileUpload(HttpServletRequest req) throws IOException {
		req.setAttribute("verbalAssociation", VerbalAssociation.correctWords);
		req.setAttribute("firstCut", VerbalAssociation.filterCutWords);
		return "/WEB-INF/views/ocr-parser.jsp";
	}

	/*
	 * 通过流的方式上传文件
	 * 
	 * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
	 */
	@RequestMapping("/imgParser")
	public String imgParser(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req) throws Exception {

		// 用来检测程序运行时间
		String fileDir = new PathUtil().getWebRoot()+"/orc-img/";
		log.info("文件存放路径:{}",fileDir);
		
		String fileExt = StringUtil.getExt(file.getOriginalFilename());
		String newFileName = new Date().getTime() +"."+ fileExt;
		String filePath = fileDir + newFileName;
		log.info("文件全路路径:{}",filePath);

		OutputStream os = null;
		InputStream is = null;
		try {
			// 获取输出流
			os = new FileOutputStream(filePath);
			// 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
			is = file.getInputStream();
			int temp;
			// 一个一个字节的读取并写入
			while ((temp = is.read()) != (-1)) {
				os.write(temp);
			}
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			os.close();
			is.close();
		}
		
		
		long startTime = System.currentTimeMillis();
		JSONObject result = OCRUtil.parseImg(filePath);
		System.out.println("文字解析耗时：" + String.valueOf(System.currentTimeMillis() - startTime) + "ms");
		
		JSONArray jsonArray = result.getJSONArray("words_result");
		if (jsonArray == null) {
			req.setAttribute("pass", false);
			return "/WEB-INF/views/ocr-parser.jsp";
		}
		String[] template = new String[] { "菜品名", "菜品价格" };
		Map<String, String> products = BaiduOcrService.getProducts(template, jsonArray);

		req.setAttribute("result", result);
		req.setAttribute("productMap", products);
		req.setAttribute("pass", true);
		req.setAttribute("verbalAssociation", VerbalAssociation.correctWords);
		req.setAttribute("firstCut", VerbalAssociation.filterCutWords);
		System.out.println(products);

		return "/WEB-INF/views/ocr-parser.jsp";
	}
	
	
	
	@RequestMapping(value="/cutImgParser",produces = "application/json;charset=utf-8")
	@ResponseBody
	public String cutImgParser(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req) throws Exception {
		// 用来检测程序运行时间
		String fileDir = new PathUtil().getWebRoot()+"/orc-img/";
		log.info("文件存放路径:{}",fileDir);
		
		String fileExt = StringUtil.getExt(file.getOriginalFilename());
		String newFileName = new Date().getTime() +"."+ fileExt;
		String filePath = fileDir + newFileName;
		log.info("文件全路路径:{}",filePath);
		OutputStream os = null;
		InputStream is = null;
		try {
			// 获取输出流
			os = new FileOutputStream(filePath);
			// 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
			is = file.getInputStream();
			int temp;
			// 一个一个字节的读取并写入
			while ((temp = is.read()) != (-1)) {
				os.write(temp);
			}
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			os.close();
			is.close();
		}
		ArrayList<Product> products = BaiduOcrService.getProducts(null, filePath);
		JSONArray jsonArray = new JSONArray(products);
		
		return jsonArray.toString();
	}
	
	
	 @RequestMapping(value = "/getProdct", method = RequestMethod.POST)
	public String getProdct(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest req){
		
		String fileDir="";
		try {
			fileDir = new PathUtil().getWebRoot()+"/orc-img/";
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		log.info("文件存放路径:{}",fileDir);
		String fileExt = StringUtil.getExt(file.getOriginalFilename());
		String newFileName = new Date().getTime() +"."+ fileExt;
		String filePath = fileDir + newFileName;
		log.info("文件全路路径:{}",filePath);
		StringBuffer buffer = new StringBuffer();
		long startTime = System.currentTimeMillis();
		System.out.println("newFileName=" + newFileName);
		OutputStream os = null;
		InputStream is = null;
		try {
			// 获取输出流
			os = new FileOutputStream(filePath);
			// 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
			is = file.getInputStream();
			int temp;
			// 一个一个字节的读取并写入
			while ((temp = is.read()) != (-1)) {
				os.write(temp);
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		Map<String, String> products = new LinkedHashMap<String, String>();
		
		String new21 = fileDir+"21-"+newFileName;
		Integer[] pixel = ImageUtil.getImagePixel(filePath);
		ImageUtil.cutImage(0, 0, pixel[0]/2, pixel[1], filePath, new21);//截取前半截
		
		String new22 = fileDir+"22-"+newFileName;
		ImageUtil.cutImage(pixel[0]/2, 0, pixel[0], pixel[1], filePath, new22);//截取后半截
		
		String[] files = new String[]{new21,new22};
		for(String path : files){
			long endTime = System.currentTimeMillis();
			JSONObject result = OCRUtil.parseImg(path);
			buffer.append(result.toString());
			System.out.println("文字解析耗时：" + String.valueOf(endTime - startTime) + "ms");
			
			JSONArray jsonArray = result.getJSONArray("words_result");
			if (jsonArray == null) {
				req.setAttribute("pass", false);
				return "/WEB-INF/views/ocr-parser.jsp";
			}
			String[] template = new String[] { "菜品名", "菜品价格" };
			products.putAll(BaiduOcrService.getProducts(template, jsonArray));
		}
		
		req.setAttribute("result", buffer);
		req.setAttribute("productMap", products);
		req.setAttribute("pass", true);
		req.setAttribute("verbalAssociation", VerbalAssociation.correctWords);
		req.setAttribute("firstCut", VerbalAssociation.filterCutWords);
		System.out.println(products);
		 
		return "/WEB-INF/views/ocr-parser.jsp";
	}
	

	// test
	public static void main(String[] args) {
		char chr = '.';
		System.out.println((int) chr);

//		System.out.println(OCRUtil.parseImg("D:\\mytools\\apache-tomcat-8.0.52\\webapps\\ocr-img\\1533607639156test3.png").toString(2));
		System.out.println(OCRUtil
				.parseImg("http://localhost:8080/ocr-img/1533607536142test3.png").toString(2));
	}

}
